import base64
import os
from collections import Counter
from datetime import datetime

import jieba
from flask import Flask, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

from recommend import recommend_clothes
from test import fake_data_content, fake_data_title

app = Flask(__name__)

# SQLAlchemy 数据库连接 URI
app.config["SQLALCHEMY_DATABASE_URI"] = (
    "mysql+pymysql://root:0430@localhost:3306/cloth_room"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class Work(db.Model):
    __tablename__ = "work"  # 表名

    # 字段定义
    work_id = db.Column(db.String(255), primary_key=True, comment="作品唯一标识，自增主键")
    user_id = db.Column(db.String(255), nullable=False, comment="用户ID（作品作者），非空")
    work_title = db.Column(db.String(20), nullable=False, comment="作品标题，非空")
    work_content = db.Column(db.String(255), nullable=False, comment="作品文字描述，非空")
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment="发布时间，非空，默认为当前时间")
    user_name = db.Column(db.String(255), nullable=True, comment="作者名称")
    index_img = db.Column(db.String(255), nullable=True, comment="封面图片")
    avatar_img = db.Column(db.String(255), nullable=True, comment="作者头像")

    def __repr__(self):
        return f"<Work work_id={self.work_id} title={self.work_title}>"

class CityWeather(db.Model):
    __tablename__ = "city_weather"  # 表名

    # 字段定义
    city_id = db.Column(db.String(255), primary_key=True, comment="城市唯一标识")
    city = db.Column(db.String(255), nullable=True, comment="城市名称")
    province = db.Column(db.String(255), nullable=True, comment="省名称")
    predict_id = db.Column(db.String(255), nullable=True, comment="天气预测表id")

    def __repr__(self):
        return f"<CityWeather city_id={self.city_id} city={self.city}>"

class PredictWeather(db.Model):
    __tablename__ = "predict_weather"  # 表名

    # 字段定义
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="没什么含义的主键")
    predict_id = db.Column(db.String(255), nullable=True, comment="城市预测天气外键")
    predict_date = db.Column(db.Date, nullable=True, comment="预测日期")
    day_weather = db.Column(db.String(255), nullable=True, comment="白天天气")
    day_temp = db.Column(db.String(255), nullable=True, comment="白天温度")
    night_weather = db.Column(db.String(255), nullable=True, comment="夜晚天气")
    night_temp = db.Column(db.String(255), nullable=True, comment="夜晚温度")
    day_wind = db.Column(db.String(255), nullable=True, comment="白天风向")
    day_power = db.Column(db.String(255), nullable=True, comment="白天风强")
    night_wind = db.Column(db.String(255), nullable=True, comment="夜晚风向")
    night_power = db.Column(db.String(255), nullable=True, comment="夜晚风强")

    def __repr__(self):
        return (f"<PredictWeather id={self.id} predict_id={self.predict_id} "
                f"predict_date={self.predict_date}>")

# Clothes 模型类
class Clothes(db.Model):
    __tablename__ = "clothes"  # 表名

    clothes_id = db.Column(db.String(255), primary_key=True, comment="衣服唯一标识，自增主键")
    user_id = db.Column(db.String(255), nullable=False, comment="用户ID，表示衣服属于哪个用户")
    clothes_type = db.Column(db.String(255), nullable=False, comment="衣服类别，非空")
    create_time = db.Column(db.DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"), comment="上传时间，非空，默认为当前时间")
    clothes_lables = db.Column(db.String(255), nullable=True, comment="衣服标签，如颜色等")

    def __repr__(self):
        return f"<Clothes clothes_id={self.clothes_id} clothes_type={self.clothes_type}>"

# Image 模型类
class IG(db.Model):
    __tablename__ = "image"  # 表名

    image_id = db.Column(db.String(255), primary_key=True, comment="图片唯一标识，自增主键")
    image_url = db.Column(db.String(255), nullable=False, server_default=text('@/static/logo.png'), comment="图片URL，非空，默认为系统默认图片")

    def __repr__(self):
        return f"<Image image_id={self.image_id} image_url={self.image_url}>"

@app.route('/wordCloud', methods=['GET'])
def render_wordcloud():  # put application's code here
    # 查询所有作品
    works = Work.query.all()
    # 提取所有作品的标题
    work_titles = [work.work_title for work in works]
    # 对 work_title 进行分词并统计词频
    words = []
    for title in work_titles:
        words.extend(jieba.lcut(title))  # 使用精确模式分词
    word_counts = Counter(words)  # 统计词频
    # 过滤掉单个字符的词
    word_data = [{"name": word, "value": count} for word, count in word_counts.items() if len(word) > 1]
    # 如果需要添加一些假数据，可以在这里扩展
    word_data.extend(fake_data_content)
    # 创建响应对象
    response = make_response(jsonify(word_data))
    # 设置响应头
    response.headers['Content-Type'] = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

@app.route('/wordCloudTitle', methods=['GET'])
def render_wordcloud_title():  # put application's code here
    works = Work.query.all()
    work_contents = [work.work_content for work in works]
    # 对 work_content 进行分词并统计词频
    words = []
    for content in work_contents:
        words.extend(jieba.lcut(content))  # 使用精确模式分词
    word_counts = Counter(words)  # 统计词频
    word_data = [{"name": word, "value": count} for word, count in word_counts.items() if len(word) > 1]
    word_data.extend(fake_data_title)
    # 创建响应对象
    response = make_response(jsonify(word_data))

    # 设置响应头为 HTTPS（确保你的服务器支持 HTTPS）
    response.headers['Content-Type'] = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'

    return response

@app.route('/recommand', methods=['GET'])
def recommand():
    # 根据 city_id 查询 CityWeather 表
    city_weather = CityWeather.query.filter_by(city_id='CT20241029105032075').first()
    predict_weather = PredictWeather.query.filter_by(predict_id=city_weather.predict_id).first()
    recommend_list = recommend_clothes(predict_weather)
    # 用于存储结果的列表
    result = []

    # 遍历每种类型，随机获取 1 件衣服的 ID 和对应的图片 URL
    for clothes_type in recommend_list:
        # 使用数据库的随机函数随机选择 1 件衣服
        random_clothes = Clothes.query.filter_by(clothes_type=clothes_type).order_by(db.func.random()).first()
        if random_clothes:
            # 查询对应的图片 URL
            image = IG.query.filter_by(image_id=random_clothes.clothes_id).first()
            if image:
                # 将图片路径转换为 Base64 编码
                image_path = image.image_url
                if os.path.exists(image_path):
                    with open(image_path, "rb") as image_file:
                        encoded_string = 'data:image/png;base64,'+base64.b64encode(image_file.read()).decode('utf-8')
                        result.append({
                            "imgId": random_clothes.clothes_id,
                            "text": random_clothes.clothes_type,
                            "iconPath": encoded_string
                        })
                else:
                    result.append({
                        "imgId": random_clothes.clothes_id,
                        "text": random_clothes.clothes_type,
                        "iconPath": None  # 如果文件路径不存在，返回 None
                    })
            else:
                result.append({
                    "imgId": random_clothes.clothes_id,
                    "text": random_clothes.clothes_type,
                    "iconPath": None  # 如果没有找到图片，返回 None
                })

    data = {
        "msg": "Hello, this is secure data!",
        "status": 200,
        "data": result,
        "code": 200
    }
    # 返回推荐结果
    # 创建响应对象
    response = make_response(jsonify(data))
    # 设置响应头为 HTTPS（确保你的服务器支持 HTTPS）
    response.headers['Content-Type'] = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response


if __name__ == '__main__':
    app.run(host='127.0.0.1',port=7999)
